package com.sl.au.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.BusinessInspectDetail;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.entity.Option;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.OptionService;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 商户巡检
 * 
 * @author heguangchuan
 *
 */
@RestController
@RequestMapping(value = "/ui/bussinessInspection")
public class BussinessInspectionController extends BaseController {

	@Autowired
	private BussinessInspectionService bussinessInspectionService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	private OptionService optionService;

	@RequestMapping("/exportToExcel")
	public void exporToExcel(@RequestParam(value = "key", required = false) String key, HttpServletResponse response) {

		List<BussinessInspection> inspections = bussinessInspectionService.getInspections(0, Integer.MAX_VALUE, key,
				null, null);
		// 第一步创建workbook
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步创建sheet
		HSSFSheet sheet = wb.createSheet("巡检记录");
		// 第三步创建行row:添加表头0行
		HSSFCellStyle style = wb.createCellStyle();
		HSSFRow row = sheet.createRow(0);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 第四步创建单元格
		HSSFCell cell0 = row.createCell(0); // 第一个单元格
		cell0.setCellValue("商户名称");
		cell0.setCellStyle(style);

		HSSFCell cell1 = row.createCell(1);
		cell1.setCellValue("商户地址");
		cell1.setCellStyle(style);

		HSSFCell cell2 = row.createCell(2);
		cell2.setCellValue("经营范围");
		cell2.setCellStyle(style);

		HSSFCell cell3 = row.createCell(3);
		cell3.setCellValue("管理员");
		cell3.setCellStyle(style);

		HSSFCell cell4 = row.createCell(4);
		cell4.setCellValue("检查情况");
		cell4.setCellStyle(style);

		HSSFCell cell5 = row.createCell(5);
		cell5.setCellValue("巡检人员");
		cell5.setCellStyle(style);

		HSSFCell cell6 = row.createCell(6);
		cell6.setCellValue("巡检电话");
		cell6.setCellStyle(style);

		HSSFCell cell7 = row.createCell(7);
		cell7.setCellValue("检查时间");
		cell7.setCellStyle(style);

		HSSFCell cell8 = row.createCell(8);
		cell8.setCellValue("备注");
		cell8.setCellStyle(style);

		// 写入数据
		int totalRows = inspections.size();
		for (int i = 1; i <= totalRows; i++) {
			BussinessInspection bi = inspections.get(i - 1);
			BusinesssellerBaseInfo b = bi.getBusinesssellerBaseInfo();
			HSSFRow r = sheet.createRow(i);
			HSSFCell c0 = r.createCell(0);
			c0.setCellValue(b.getShopName());

			HSSFCell c1 = r.createCell(1);
			c1.setCellValue(b.getShopAdress());

			HSSFCell c2 = r.createCell(2);
			c2.setCellValue(b.getManagementRange());

			HSSFCell c3 = r.createCell(3);
			c3.setCellValue(b.getManagementPerson().getName());

			HSSFCell c4 = r.createCell(4);
			c4.setCellValue(bi.getInspectCondition().getTitle());

			HSSFCell c5 = r.createCell(5);
			c5.setCellValue(bi.getUser().getName());

			HSSFCell c6 = r.createCell(6);
			c6.setCellValue(bi.getUser().getContactType());

			HSSFCell c7 = r.createCell(7);
			c7.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bi.getInspectDate()));

			HSSFCell c8 = r.createCell(8);
			c8.setCellValue(bi.getRemark());
		}

		OutputStream ouputStream = null;
		String fileName = "inspection.xls";
		response.setHeader("Content-disposition", fileName);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		response.setHeader("Pragma", "No-cache");

		try {
			ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				wb.close();
				ouputStream.close();
			} catch (Exception e) {

				e.printStackTrace();
			}

		}

		// return MsgHelper.success();
	}

	@RequestMapping("/findOptsByGroup")
	public MsgHelper findOptsByGroup() {

		return MsgHelper.success()//
				.put("noneOpt", optionService.getRepository().findByGroupAndTitle("其他问题", "无"))//
				.put("environment", optionService.getRepository().findByGroup("环境卫生"))//
				.put("cityOrder", optionService.getRepository().findByGroup("市容秩序"))//
				.put("greenCondition", optionService.getRepository().findByGroup("绿化美化"));
	}

	@RequestMapping(value = "/listAllSellers", method = RequestMethod.GET)

	public MsgHelper listAllSeller() {
		List<BusinesssellerBaseInfo> infos = businesssellerBaseInfoService.findAll();
		return MsgHelper.success().put("sellers", infos);
	}

	@RequestMapping("/findById/{id}")

	public MsgHelper findById(@PathVariable("id") String id) {
		BussinessInspection info = bussinessInspectionService.findById(id);
		return MsgHelper.success().put("info", info);
	}

	@RequestMapping("/pageOnPhone")
	public MsgHelper getPageInfoOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");// 这个商户的id
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}

		// 初始化页面
		List<BussinessInspection> uncheckedInfo = bussinessInspectionService.findByTimeAndUncheck(0, 30, identify, null,
				null);
		List<BussinessInspection> checkedInfo = bussinessInspectionService.findByCheck(0, 30, identify, null, null);

		return MsgHelper.success().put("uncheckedInfo", uncheckedInfo).put("checkedInfo", checkedInfo);
	}

	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	public Map<String, Object> saveOrUpdate(MultipartHttpServletRequest requests) {
		MultipartFile file = requests.getFile("file");

		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;

		BusinesssellerBaseInfo info = businesssellerBaseInfoService
				.findByBussinessSellerId(request.getParameter("bussinessId"));

		// 获取当前Check图片的存储路径
		String url = "";
		if (file != null && !file.isEmpty()) {
			// 注意路径的构建
			url = getUploadFilePath(this.fileUploadPath, "img/inspection", file);
		}

		JSONObject project = JSONObject.fromObject(request.getParameter("bussinessInspection"));
		BussinessInspection bussinessInspection = (BussinessInspection) JSONObject.toBean(project,
				BussinessInspection.class);

		bussinessInspection.setBusinesssellerBaseInfo(info);
		bussinessInspection.setInspectDate(new Date());
		bussinessInspection.setUser(getMyAccount().getUser());
		bussinessInspection.setPictureAddr(url);

		List<BusinessInspectDetail> dlist = new ArrayList<>();

		JSONArray businessInspectDetailList = JSONArray.fromObject(request.getParameter("businessInspectDetail"));
		for (int i = 0; i < businessInspectDetailList.size(); i++) {
			JSONObject jsonObject = businessInspectDetailList.getJSONObject(i);
			BusinessInspectDetail businessInspectDetail = (BusinessInspectDetail) JSONObject.toBean(jsonObject,
					BusinessInspectDetail.class);
			if (needCheck(businessInspectDetail, businessInspectDetailList)) {
				bussinessInspection.setNeedCheck((byte) 0);// 不需要检查
			} else {
				bussinessInspection.setNeedCheck((byte) 1);// 需要检查
			}
			businessInspectDetail.setCreateTime(new Date());
			businessInspectDetail.setInspection(bussinessInspection);
			file = requests.getFile(businessInspectDetail.getInspectOpt().getId());

			if (file != null && !file.isEmpty()) {
				// 注意路径的构建
				url = getUploadFilePath(this.fileUploadPath, "img/inspectDetail", file);
				businessInspectDetail.setPicAddr(url);
			}

			dlist.add(businessInspectDetail);
		}
		bussinessInspectionService.saveMany(bussinessInspection, dlist);
		// bussinessInspectionService.save(bussinessInspection);
		// businessInspectDetailService.save(dlist);
		code = 1;
		map.put("code", code);
		return map;
	}

	private boolean needCheck(BusinessInspectDetail bd, JSONArray list) {
		Option opt = optionService.getRepository().findOne(bd.getInspectOpt().getId());

		boolean b = list.size() == 1 && "其他问题".equals(opt.getGroup()) && "无".equals(opt.getTitle());
		return b;
	}

	/**
	 * 
	 * @param map
	 *            存放到页面的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.GET)
	public ModelAndView saveUI(Map<String, Object> map) {
		map.put("id", "");
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessInspection/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("options", optionService.getRepository().findByGroup("巡检状况"));
			return modelAndView;
		} else {
			return createLayoutView("bussinessInspection/saveOrUpdate");
		}
	}

	/**
	 * 
	 * @param id
	 *            到修改页面传的id
	 * @param map
	 *            存放到页面所需要的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate/{id}", method = RequestMethod.GET)
	public ModelAndView updateUI(@PathVariable("id") String id, Map<String, Object> map) {
		map.put("id", id);

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessInspection/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("options", optionService.getRepository().findByGroup("巡检状况"));
			return modelAndView;
		} else {
			return createLayoutView("bussinessInspection/saveOrUpdate");
		}
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)

	public MsgHelper delete(@PathVariable(value = "id") String id) {
		bussinessInspectionService.deleteById(id);
		return MsgHelper.success();
	}

	/**
	 * 获取商户巡检分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		List<BussinessInspection> inspections = null;
		String key = request.getParameter("key");
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		// 移动端
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			// 只显示最新的10页
			inspections = bussinessInspectionService.getInspections(0, 10, identify, null, null);
		} else {
			// PC端

			if (StringUtils.hasText(key)) {
				inspections = bussinessInspectionService.getInspections(start, length, key, null, null);
			} else {
				inspections = bussinessInspectionService.getPage(start, length, null, null, null);
			}
		}

		int count = bussinessInspectionService.getCount(key);
		map.put("data", inspections);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 进入巡检首页
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/bussinessInspection/indexOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("device", device);
			modelAndView.addObject("url", url);

		} else {
			// PC端
			modelAndView = createLayoutView("bussinessInspection/bussinessInspection");
		}
		return modelAndView;
	}
}
